import CommonModal from '@/components/CommonModal';
import Typography from '@/views/components/Typography';
import CommonLoading from '@/components/CommonLoading';
import TaobaoCode from '../TaobaoCode';
import { useEffect, useState } from 'react';
import { Alert } from 'antd';
import { countOrderSum, checkHasTaobao } from '../../config/CheckConfig';
import { agreeWithRefund } from '../../services';

/** 买家已退货，同意退款 */
function AgreeRefundReturned(props) {
	const { item, selectKeys, tableList, handleOk, handleCancel } = props;
	const { scene } = item;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const [visible, setVisible] = useState(false);
	const [childAccount, setChildAccount] = useState({});

	useEffect(() => {
		setOpen(true);
	}, [])

	const onOk = async () => {
		const isTabobao = checkHasTaobao(selectKeys, tableList);
		if (isTabobao) {
			handleRefund(null, (val) => {
				const list = val.filter(v => v.gatewayOperateVO.errorCode == 2001);
				const isModal = list.length > 0 ? true : false;
				if(isModal) {
					const obj = val[0] || {};
					setChildAccount(obj);
					setVisible('taobao');
				} else {
					setIsOk(true);
					setOpen(false);
				}
			});
		} else {
			handleRefund();
		}
	}

	//点击确定
	const handleRefund = async (code, cb) => {
		setLoading(true);
		const params = {
			ids: selectKeys,
			buttonType: 3
		}
		if (code) {
			params.code = code;
			params.timeMillis = childAccount.gatewayOperateVO?.timeMillis;
		}
		const { success, data } = await agreeWithRefund(params);
		setLoading(false);
		if (success) {
			if (cb) {
				cb(data);
			} else {
				setIsOk(true);
				setOpen(false);
			}
		}
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk()
		} else {
			handleCancel();
		}
	}

	//当前满足条件数量
	const countNum = countOrderSum(scene, selectKeys, tableList);

	//淘宝验证码弹框
	const TaobaoCodeProps = {
		childAccount: childAccount?.subUserName,
		handleOk(val) {
			setVisible(null);
			handleRefund(val);
		},
		handleCancel() {
			setVisible(null);
		}
	}

	return (
		<CommonModal title="买家已退货，同意退款" afterClose={afterClose} open={open} width="552px" onOk={onOk} onCancel={onCancel}>
			<Alert showIcon type="info" message="同意退款后，“退款成功”状态会同步线上三方平台，且资金会直接退给买家；" />
			<div style={{ color: '#333', fontSize: '14px', marginTop: '16px' }}>
				<div>
					买家已退货，同意退款，只限操作以下二种状态的售后单：
				</div>
				<div style={{ margin: '12px 0' }}>
					已发货退货退款+买家已退货：<Typography type="error">{countNum[0]}</Typography>
				</div>
				<div>
					已发货退货退款+卖家已收货：<Typography type="error">{countNum[1]}</Typography>
				</div>
			</div>
			{visible == 'taobao' && <TaobaoCode {...TaobaoCodeProps} />}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default AgreeRefundReturned;
